import React from "react";
import {connect} from "react-redux";
import action from "../store/action";
import { Modal, Checkbox, Table, Form, Select, Tag, Card, Row, Col, Button, Layout, Input, Menu, Icon, Tree  } from 'antd';
import {addFunArgApi, listFunArgApi, removeArgApi, fileListApi, addFunArgByFieldIdApi} from "../api/projectConfig";
import {message} from "antd/lib/index";
import Qs from 'qs'
import {withRouter} from "react-router-dom";
import {Config as config} from "../utils/Constants";

const { TextArea } = Input;
const FormItem = Form.Item;
const Option = Select.Option;
const confirm = Modal.confirm;

class ControllerFunParams extends React.Component {

    funInfo;
    argShowCallBack;

    state = {
        visible: false,
        baseTypeVisible: false,
        args: [],
        argTypeName: '',
        voList: [],
    }

    constructor(props) {
        super(props);
    }

    componentDidMount() {
        this.props.onRef(this)
    }

    handleCancel = () => {
        this.setState({ ...this.state, visible: false });
    }

    argTypeHandleChange = (value) => {
        console.info('argType=' + value);

        var baseTypeVisible = false;
        var argTypeName = 'select vo';
        if(value == 'base') {
            baseTypeVisible = true;
            argTypeName = 'String';
        }

        this.setState({
            ...this.state,
            baseTypeVisible: baseTypeVisible,
            argTypeName: argTypeName
        });
    }

    addFunArgs = (e) => {
        e.preventDefault();


        let that = this;
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                console.log('Received values of form: ', values);

                let {argTypeName, argTypeId} = that.state;
                let funInfo = that.funInfo;

                let formData = that.props.form.getFieldsValue();
                formData.funId = funInfo.id

                formData.argTypeName = argTypeName
                formData.argTypeId = argTypeId

                let ret = addFunArgApi(formData);
                ret.then((res)=>{
                    message.success('保存成功！');
                    that.loadArgs();

                    /** 清除输入框 */
                    that.props.form.setFieldsValue({name:'', collectionType:'single'});
                    that.argShowCallBack();

                });
            }
        });
    }

    addFunArgsFromField = (fieldId, pid, fieldType) => {

        // funId pid fieldId
        let funId = this.funInfo.id
        let formData = {funId, fieldId, pid, fieldType}
        let that = this;
        let ret = addFunArgByFieldIdApi(formData);
        ret.then((res)=>{
            message.success('启用成功！');
            that.loadArgs();
            that.argShowCallBack();
        })
    }


    loadArgs = ()=>{

        let funArgsData = listFunArgApi(this.funInfo.id)
        funArgsData.then(res=>{
            let args = res.data.data
            this.setState({ ...this.state, args: args });

        })
    }

    fetchVoList = ()=>{

        let {location: {search}} = this.props,
            {projectId = 0} = Qs.parse(search.substr(1)) || {};

        console.info('projectId=' + projectId);

        let voListRet = fileListApi(projectId, 'vo')
        voListRet.then(res=>{
            this.setState({ ...this.state, voList: res.data.data });
        })

    }

    removeArg = (argId)=>{
        console.info('argId=' + argId);
        let that = this;
        confirm({
            title: '是否确定删除此参数?',
            content: '点击确定将删除此参数',
            onOk() {
                let ret = removeArgApi(argId);
                ret.then(res=>{
                    that.loadArgs();
                    that.argShowCallBack();
                })
            },
            onCancel() {
                console.log('Cancel');
            },
        });

    }

    showModal = (funInfo, argShowCallBack) => {
        if(funInfo) {
            this.funInfo = funInfo
        }
        if(argShowCallBack) {
            this.argShowCallBack = argShowCallBack
        }

        this.setState({
            ...this.state,
            visible: true,
        });

        this.loadArgs();
    }

    render() {

        let colors = ['magenta', 'red', 'volcano', 'orange', 'gold', 'gold', 'green', 'cyan', 'blue', 'geekblue', 'purple'];
        let {args, visible, baseTypeVisible, argTypeName, voList} = this.state

        const data = args;

        const columns = [{
            title: 'ParamName',
            dataIndex: 'name',
            width: '20%',
            key: 'name',
            /* vo对象需要添加图标显示 */
            //render: (text, row, index) => <span>{(row.nodeType == 'children' ? '-' : '') + text}</span>
        }, {
            title: 'Type',
            dataIndex: 'argTypeName',
            key: 'argTypeName',
            width: '16%',
        }, {
            title: 'Comment',
            dataIndex: 'comment',
            key: 'comment',
            width: '20%',
        }, {
            title: 'Validator',
            dataIndex: 'validate',

            key: 'validate',
            render: (text, row, index) =>  {

                // 处理下内容
                if(row.valid) {
                    row.valid = eval(row.valid);
                }
                return (<span>
                    {row.valid ? row.valid.map((v, ii)=> {
                        let colorIndex = parseInt(Math.random() * colors.length) % colors.length;
                        return <Tag key={index + '_' + ii} color={colors[colorIndex]}>{v}</Tag>}) : ''}

                    {row.id ?
                    <Button onClick={()=>{

                        this.props.showValidatePanel(row)
                    }} type="primary" size="small">+</Button>
                        : '-'}
                </span>)
            }
        }, {
            title: 'Operate',
            dataIndex: 'address',
            width: '30%',
            key: 'operate',
            render: (text, row, index) => {

                // row.nodeType == 'children'

                return (<div>
                    {row.id
                    ?
                    <Button onClick={this.removeArg.bind(this, row.id)} type="danger" size="small">删除</Button>
                    :
                    <Button onClick={this.addFunArgsFromField.bind(this, row.fieldId, row.pid, row.fieldType)} type="danger" size="small">启用</Button>}
                </div>)
            }
        }];


        const { getFieldDecorator, setFieldsValue } = this.props.form;

        return (
            <Modal
                width={900}
                visible={visible}
                keyboard={false}
                maskClosable={false}
                title="params"
                onOk={this.handleOk}
                onCancel={this.handleCancel}
                footer={[
                    <Button key="back" onClick={this.handleCancel}>关闭</Button>
                ]}
            >
                <Form layout="inline" className="form_item_4" onSubmit={this.addFunArgs}>

                    <FormItem  label="参数" >
                        {getFieldDecorator('argType', {
                            initialValue: 'vo',
                            rules: [{ required: true, message: 'is not null!' }],
                        })(
                            <Select onChange={this.argTypeHandleChange} style={{width: '90px'}} placeholder="数据类型">
                                <Option value="base">base</Option>
                                <Option value="vo">vo</Option>
                            </Select>
                        )}

                    </FormItem>

                    {baseTypeVisible ?
                        (<FormItem>
                            <Select value={argTypeName} onChange={(value)=>{
                                this.setState({...this.state, argTypeName: value});
                            }} style={{width: '120px'}} placeholder="基本类型">
                                {config.DATA_TYPE_LIST.map((value, index) => <Option key={value}>{value}</Option>)}
                            </Select>
                        </FormItem>)
                        : (
                            <FormItem>
                                <Select value={argTypeName} onFocus={(value)=>{
                                    this.fetchVoList()
                                }} onChange={(index)=>{
                                    this.setState({...this.state, argTypeName: voList[index].name, argTypeId: voList[index].id});
                                    let argName = voList[index].name;
                                    argName = argName[0].toLowerCase()+argName.substring(1, argName.length);
                                    setFieldsValue({name: argName});
                                }} style={{width: '220px'}} placeholder="VO类型">
                                    {voList.map((vo, index) => <Option key={index}>{vo.name}</Option>)}
                                </Select>
                            </FormItem>
                        )
                    }

                    <FormItem >
                        {getFieldDecorator('name', {
                            rules: [{ required: true, message: 'is not null!' }],
                        })(
                            <Input placeholder="参数名称" />
                        )}
                    </FormItem>

                    <FormItem  label="集合类型" >
                        {getFieldDecorator('collectionType', {
                            initialValue: 'single',
                            rules: [{ required: true, message: 'is not null!' }],
                        })(
                            <Select style={{width: '90px'}} placeholder="集合类型">
                                <Option value="single">单值</Option>
                                <Option value="list">List</Option>
                                <Option value="map">Map</Option>
                                <Option value="set">Set</Option>
                            </Select>
                        )}
                    </FormItem>

                    <Button type="primary" htmlType="submit" icon="save">添加</Button>
                </Form>

                {/* table list */}
                <Table columns={columns} rowKey={record => record.id} dataSource={data} pagination={false} />

            </Modal>
        )
    }
}





const _ControllerFunParams = Form.create()(ControllerFunParams);
const __ControllerFunParams = withRouter(connect(state => ({...state.controllerParams}), action.controllerParams)(_ControllerFunParams))

export default __ControllerFunParams
